package cn.xxm.dongbao.user.secure.access;

import org.springframework.http.HttpStatus;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.access.AccessDeniedHandler;

public class DefaultAccessDeniedHandlerImpl implements AccessDeniedHandler {
    private static final String ERROR_MSG = "InValid CSRF Token";
    /**
     * The error page.
     */
    private String errorPage;

    /**
     * Handle.
     * @param request the request
     * @param response the response
     * @param accessDeniedException the access denied exception
     * @throws IOException the IO exception
     * @throws ServletException the servlet exception
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        if (response.isCommitted()) {
            return;
        }
        if (errorPage != null) {
            request.setAttribute(WebAttributes.ACCESS_DENIED_403, accessDeniedException);
            response.setStatus(HttpStatus.FORBIDDEN.value());
            RequestDispatcher dispatcher = request.getRequestDispatcher(errorPage);
            if (dispatcher != null) {
                dispatcher.forward(request, response);
            }
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            if (response.getWriter() != null) {
                response.getWriter().write(ERROR_MSG);
            }
        }
    }

    /**
     * Sets the error page.
     * @param errorPage the error page
     */
    public void setErrorPage(String errorPage) {
        if ((errorPage != null) && !errorPage.startsWith("/")) {
            throw new IllegalArgumentException("The errorPage must begin with '/'");
        }
        this.errorPage = errorPage;
    }

}